from loguru import logger
from fastapi import APIRouter,Depends
from sqlalchemy.orm import Session
from sqlalchemy import desc
from db.mysql import get_db
from vendor.extend.courier import *
from model.equipment import Equipment
from model.equipment_drill import Item,UpdateInfo,EquipmentDrill as EquipmentDrillTable

from vendor.extend.conversion import is_positive_integer

EquipmentDrill = APIRouter()

@EquipmentDrill.post('/settings')
async def settings(item: Item, db: Session = Depends(get_db)):
    # 解析JSON数据
    item_dict = item.dict()
    result = db.query(Equipment.id).filter_by(id=item_dict.get('equipment_id',0)).first()
    if not result:
        return Error(msg='工作面不存在')

    ed_data=EquipmentDrillTable(equipment_id=result.id,
                            identifier= item_dict.get('identifier',''),
                            channel= item_dict.get('channel',''),
                            type= item_dict.get('type',''),
                            x=item_dict.get('work_face_distance',0),
                            y=item_dict.get('vertical_threshold',0),
                            z=item_dict.get('vertical_threshold',0),
                            line=item_dict.get('line',''),
                            create_time=int(time.time())
                        )

    try:
        # 执行一些数据库操作
        db.add(ed_data)
        db.flush()
        db.commit()
        db.refresh(ed_data)
    except Exception as e:
        # 手动回滚会话并重新抛出异常
        db.rollback()
        logger.error("钻孔信息 添加 出错:{}", e)
        return Error(msg='钻孔信息 添加失败',data=e)
    finally:
        db.close()

    return Success(data={'drill_id':ed_data.id,'equipment_id':ed_data.equipment_id,'create_time':ed_data.create_time})



@EquipmentDrill.post('/update')
async def update(item:UpdateInfo, db: Session = Depends(get_db)):
    item_dict = item.dict()
    equipment={
        'equipment_id': item_dict.get('equipment_id',0),
        'identifier': item_dict.get('identifier',''),
        'channel': item_dict.get('channel',''),
        'type':item_dict.get('type',''),
        'x':item_dict.get('x',0),
        'y':item_dict.get('x',0),
        'z':item_dict.get('x',0),
        'line':item_dict.get('line',''),
        'update_time':int(time.time())
    }

    try:
        # 执行一些数据库操作
        db.query(EquipmentDrillTable).filter_by(id=item_dict.get('drill_id',0)).update(equipment)
        db.commit()
    except Exception as e:
        # 手动回滚会话并重新抛出异常
        db.rollback()
        logger.error("钻孔信息 更新 出错:{}", e)


    return Success(data=equipment)


@EquipmentDrill.get('/list')
async def getlist(equipment_id:int, db: Session = Depends(get_db)):
    if not equipment_id:
        return Error(msg='equipment_id参数错误')

    list_data=db.query(EquipmentDrillTable).filter_by(equipment_id=equipment_id).order_by(desc("id")).all()
    data_list=[]
    disabled=None
    for info in list_data:
        data_list.append({
            "id":info.id,
            "equipment_id":info.equipment_id,
            "identifier":info.identifier,
            "type":info.type,
            "channel":info.channel,
            "x":info.x,
            "y":info.y,
            "z":info.z,
            "line":info.line,
            "create_time":info.create_time,
            "update_time":info.update_time
        })

    return Success(data=data_list)


@EquipmentDrill.get('/info')
async def getinfo(drill_id:int, db: Session = Depends(get_db)):
    if not is_positive_integer(drill_id):
        return Error(msg='传感器ID必须为正整数')
    info = db.query(EquipmentDrillTable).filter_by(id=drill_id).first()
    if info:
        return Success(data={
            "id":info.id,
            "equipment_id":info.equipment_id,
            "identifier":info.identifier,
            "type":info.type,
            "channel":info.channel,
            "x":info.x,
            "y":info.y,
            "z":info.z,
            "line":info.line,
            "create_time":info.create_time,
            "update_time":info.update_time
        })
    else:
        return Error(msg='未找到钻孔相关数据')